//图片加载组件

import { Suspense } from "react";
import PropTypes from "prop-types";
// 避免多次 组件刷新，导致数据刷新，在组件外部，声明变量，进行缓存
const imageCache = new Map();
//图片加载组件
function ImageLoader({ src }) {
  //预加载图片并获取资源
  const resource = preloadImage(src);
  return <img src={resource.read()} />;
}
ImageLoader.propTypes = {
  src: PropTypes.string.isRequired,
};
function preloadImage(src) {
  if (imageCache.has(src)) {
    return imageCache.get(src);
  }
  let status = "pending";
  let result;
  const promise = new Promise((resolve, reject) => {
    const img = new Image();
    img.src = src;
    //图片加载成功之后的处理函数
    img.onload = () => {
      status = "success";
      result = src;
      resolve(src);
    };
    //图片加载失败之后的处理函数
    img.onerror = () => {
      status = "error";
      result = new Error("failed to load image");
      reject(result);
    };
  });
  //创建一个资源对象
  const resource = {
    //read方法根据状态返回不同的结果
    read() {
      if (status === "pending") throw promise;
      if (status === "error") throw result;
      return result;
    },
  };
  //将资源存入缓存
  imageCache.set(src, resource);
  return resource;
}

function App() {
  return (
    <Suspense fallback={<p>loading image...</p>}>
      <ImageLoader src="https://www.baidu.com/img/flexible/logo/pc/result.png" />
    </Suspense>
  );
}
export default App;
